Controller.TEXT = 1;

function Controller(uri, name, id, keepSession) {
	
	this.submitForm = function(form, method) {
		var inputName = document.createElement("input");
		inputName.type = "hidden";
		inputName.name = "controller";
		inputName.value = this.getName();

		form.appendChild(inputName);

		var inputId = document.createElement("input");
		inputId.type = "hidden";
		inputId.name = "id";
		inputId.value = this.getId();

		form.appendChild(inputId);

		var inputMethod = document.createElement("input");
		inputMethod.type = "hidden";
		inputMethod.name = "do";
		inputMethod.value = method;

		form.appendChild(inputMethod);

		form.action = this.getUri();
		
		form.method = "post";
		form.submit();
	};
	
	this.callMethod = function(handler, method, params, format) {
		var obj = handler[0];
		var objMethod = handler[1];
		
		var xmlHttpRequest = new XMLHttpRequest();
		var remoteMethod = this.getUri();
		xmlHttpRequest.open("POST", remoteMethod, true);
		xmlHttpRequest.onreadystatechange = (function(format) {
			return function() {
				if (xmlHttpRequest.readyState == 4) {
					switch (format) {
						case Controller.TEXT: {
							var content = xmlHttpRequest.responseText;
						} break;
						
						case Controller.JSON:
						default: {
							var content = eval(xmlHttpRequest.responseText);
						} break;
					}
					eval("obj." + objMethod + "(content);");
				}
			};
		})(format);

		var paramsString = "controller=" + this.getName() + "&do=" + method + "&id=" + this.getId();
		for (i in params) {
			paramsString += "&params[" + i + "]=" + params[i];
		}
		xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttpRequest.setRequestHeader("Content-length", paramsString.length);
		xmlHttpRequest.setRequestHeader("Connection", "close");
		xmlHttpRequest.send(paramsString);
	};

	this.href = function(method) {
		document.location.href = this.getUri() + "?controller=" + this.getName() + "&id=" + this.getId() + "&do=" + method;
	};
	
	this.getUri = function() {
		return this.uri;
	};

	this.setUri = function(uri) {
		this.uri = uri;
	};

	this.getName = function() {
		return this.name;
	};

	this.setName = function(name) {
		this.name = name;
	};

	this.getId = function() {
		return this.id;
	};

	this.setId = function(id) {
		this.id = id ? id : "";
	};

	this.getKeepSession = function() {
		return this.keepSession;
	};

	this.setKeepSession = function(keepSession) {
		this.keepSession = (keepSession != undefined) ? keepSession : false;

		if (this.keepSession) {
			controller = this;
			setInterval("Controller.ping(controller)", 10 * 60 * 1000);
		}
	};
	
	Controller.ping = function(controller) {
		controller.callMethod([controller, "pong"], "ping", {});
	};

	this.pong = function(result) {
	};

	this.uri = null;
	this.name = null;
	this.id = null;
	this.keepSession = null;

	this.setUri(uri);
	this.setName(name);
	this.setId(id);
	this.setKeepSession(keepSession);
}
